package com.yourenbang.lingyun.transaction.web.service.impl.migrate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yourenbang.lingyun.constants.BizCodeMessages;
import com.yourenbang.lingyun.core.exception.SysBizException;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.StringUtils;
import com.yourenbang.lingyun.core.util.http.HttpClientUtil;
import com.yourenbang.lingyun.transaction.web.service.migrate.CommonMigrateService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Date 2020/10/21 17:35
 * @Created by Jason
 */
@Service
public class CommonMigrateServiceImpl implements CommonMigrateService {
    @Override
    public JSONArray pullDataFromKS(String url, String jsonParam) {


        Map<String, Object> requestMap = new HashMap<>();
        Map<String, Object> dataMap = JSON.parseObject(jsonParam);
        requestMap.put("data", dataMap);
        String resultJson = null;
        try {
            for (int i = 0;i<3;i++) {
                KLog.info("【迁移】准备请求快收第{}次,url:{}, 请求参数:{}",i+1, url, requestMap);
                resultJson = HttpClientUtil.httpPostRequest(url, JSON.toJSONString(requestMap));
                KLog.info("【迁移】快收响应:{} ,url:{}, 请求参数:{}", resultJson.length()>60?resultJson.substring(0, 60):resultJson, url, requestMap);
                if (!StringUtils.isBlank(resultJson)){
                    break;
                }

            }
            //respond
            //【迁移】快收响应: ,url:http://api2.kaolakuaishou.com/query/pay/account/detail/limit, 请求参数:{data={"offset":527000,"pageSize":1000}}
        } catch (Exception e) {
            KLog.info("迁移异常:",e);
            throw new SysBizException(BizCodeMessages.UNKNOWN_ERROR, "请求快收迁移接口异常");
        }

        JSONObject resultData = JSON.parseObject(resultJson);
        if (resultData.getInteger("code")!= 0){
            return new JSONArray();
        }
        int count = resultData.getJSONObject("data").getInteger("count");
        if (count == 0) {
            return new JSONArray();
        }
        JSONArray jsonArray = resultData.getJSONObject("data").getJSONArray("list");
        return jsonArray;
    }
}
